import axios from 'axios'
import store from '@/store'
import { removeSpaces, getLocalStorage } from '@/utils/filters'
import Cookie from 'js-cookie'
import { Message } from 'element-ui'

let baseURL = process.env.VUE_APP_BASE_API
if (process.env.NODE_ENV !== 'production') {
    baseURL = localStorage.getItem('baseURL') ? localStorage.getItem('baseURL') : baseURL
}
// create an axios instance
const service = axios.create({
    baseURL: baseURL, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 300000 // request timeout
})

if (Cookie.get('token')) {
    // 让每个请求携带 token 请根据实际情况自行修改
    service.defaults.headers['Authorization'] = 'Bearer ' + Cookie.get('token')
}

let count = 0
// request interceptor
service.interceptors.request.use(
    config => {
    // do something before request is sent
    //     if (store.getters.token) {
    //         // let each request carry token
    //         // ['X-Token'] is a custom headers key
    //         // please modify it according to the actual situation
    //         config.headers['X-Token'] = getToken()
    //     }
        count++
        if (Number(getLocalStorage('userInfo', 'checkAuth')) === 1 && config.data) {
            config.data.resident = getLocalStorage('userInfo', 'realName')
        }
        store.dispatch('app/UpdateLoading', true)
        if (config.data && config.data.hosDays === '') {
            config.data.hosDays = 0
        }
        if (config.data && config.data.hosDays) {
            config.data.hosDays = Number(config.data.hosDays)
        }
        config.data = removeSpaces(config.data)
        return config
    },
    error => {
        count++
        store.dispatch('app/UpdateLoading', true)
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        count--
        store.dispatch('app/UpdateLoading', false)
        return new Promise(resolve => {
            resolve(response.data)
        })
    },
    error => {
        count--
        if (count <= 0) {
            store.dispatch('app/UpdateLoading', false)
        } else {
            store.dispatch('app/UpdateLoading', true)
        }
        store.dispatch('app/UpdateLoading', false)
        if (error.message.includes('401')) {
            Cookie.set('timeOut', 'timeOut')
            store.dispatch('user/logout').then(() => {
                // 验证失败，请重新登录
                window.location.href = '/login'
            })
        }
        if (error.message.includes('403')) {
            Message.error('无权限操作')
        }
        return Promise.reject(error)
    }
)

export default service
